#!/usr/bin/env python
# -*- coding: UTF-8 -*-
__author__ = 'Young'

from log.logUtils import logger

from pymysql import connect, cursors
from pymysql.err import OperationalError

'''
        Don't try to do things that are outside your scope, or you will fail miserably
'''
import os, sys

sys.path.append(os.path.dirname(os.path.dirname(__file__)))
from config import settings
from pymysql import connect, cursors
from pymysql.err import OperationalError
import configparser as cparser
from utils.parse_config import conf

# --------- 读取config.ini配置文件 ---------------
# cf = cparser.ConfigParser()
# cf.read(settings.TEST_CONFIG,encoding='UTF-8')
# host = cf.get("mysqlconf","host")
# port = cf.get("mysqlconf","port")
# user = cf.get("mysqlconf","user")
# password = cf.get("mysqlconf","password")
# db = cf.get("mysqlconf","db_name")

host = conf.getconf("db-master", "db_host")
port = conf.getconf("db-master", "db_port")
user = conf.getconf("db-master", "db_user")
password = conf.getRawConfig("db-master", "db_pass")
db = conf.getconf("db-master", "db_database")
db_charset = conf.getconf("db-master", "db_charset")

pass


class DB:
    """
    MySQL基本操作
    """

    def __init__(self):
        try:
            # 连接数据库
            self.conn = connect(host=host,
                                user=user,
                                password=password,
                                db=db,
                                charset=db_charset,
                                cursorclass=cursors.DictCursor
                                # cursorclass = cursors.DictCursor
                                )
            self.cursor = self.conn.cursor()
        except OperationalError as e:
            logger.error("Mysql Error %d: %s" % (e.args[0], e.args[1]))

    def transactionCommit(self):
        self.conn.commit()

    def transactionClose(self):
        self.conn.close()
        # 清除表数据

    def select(self, table_name):
        real_sql = "select * from " + table_name + ";"

        # with self.conn.cursor() as cursor:
        #     # 取消表的外键约束
        #     cursor.execute("SET FOREIGN_KEY_CHECKS=0;")
        #     cursor.execute(real_sql)
        # self.conn.commit()
        self.cursor.execute(real_sql)
        info = self.cursor.fetchall()
        logger.info(info)
        return info
        self.transactionCommit()

    # 清除表数据
    def clear(self, table_name):
        real_sql = "delete from " + table_name + ";"
        with self.conn.cursor() as cursor:
            # 取消表的外键约束
            cursor.execute("SET FOREIGN_KEY_CHECKS=0;")
            cursor.execute(real_sql)
        self.conn.commit()

    # 插入表数据
    def insert(self, table_name, table_data):
        for key in table_data:
            table_data[key] = "'" + str(table_data[key]) + "'"
        key = ','.join(table_data.keys())
        value = ','.join(table_data.values())
        real_sql = "INSERT INTO " + table_name + " (" + key + ") VALUES (" + value + ")"

        with self.conn.cursor() as cursor:
            cursor.execute(real_sql)
        self.conn.commit()

    # 关闭数据库
    def close(self):
        self.conn.close()

    # 初始化数据
    def init_data(self, datas):
        for table, data in datas.items():
            self.clear(table)
            for d in data:
                self.insert(table, d)
        self.close()


# db = DB()
if __name__ == '__main__':
    logger.debug("1111111111111111")
    DB().select("t_account_0")
